﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Runtime.CompilerServices;
using Telerik.Web.Mvc;
using FluentValidation.Mvc;
using FluentValidation;
using Microhard.Core.DBUtility;
using Microhard.Core;
using Microhard.Core.Core;
using Microhard.Framework.MVCHelper;
using Microhard.Core.Algorithm;
using Microhard.Permission.MVCFilter;
using Microhard.WeixinMP.Interfaces;
using Microhard.WeixinMP.Models;
using Microhard.Permission.MVCFilter.MVCFilter;
using System.Web.Routing;
using System.Web;
using Microhard.Permission.Models;
using System.Text.RegularExpressions;
using System.Configuration;
using Microhard.Core.Printer.POS;

namespace Microhard.Permission.Interface
{
    /// <summary>
    /// 基础Controller
    /// 程琳 2012-11-1
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// 泛型约束 new() 确保可以使用new T() http://blog.163.com/ccliushou@126/blog/static/123819096201191493859324/
    public class MicroHardBaseController<T> : Controller, IMicroHardControllerOperations<T> where T : new()
    {
        /// <summary>
        /// 接口集成实现
        /// </summary>
        protected IRepository<T> _repository;
        /// <summary>
        /// 在首页是否分页
        /// </summary>
        protected bool _isUsingPagingInIndex = true;
        protected int _pageSize = int.Parse(ConfigurationManager.AppSettings["GridPageSize"]);

        #region 操作记录
        public void LogIndex(ScopeResult scope)
        {
            //string cotrName = this.RouteData.Values["controller"].ToString();
            //if (!FilterHelper.IsSysAdminAction(cotrName))
            //{
            //    OperationLog.LogOperationData(new UserOperationLogModel
            //    {
            //        CreateTime = DateTime.Now,
            //        OperationTime = DateTime.Now,
            //        OperationName = "列表",
            //        ResourceName = cotrName,
            //        ResultStatus = true,
            //        UserName = scope.CurrentUserName,
            //        UserRealName = scope.CurrentUserRealName
            //    });
            //}
        }

        public void LogCreate(ScopeResult scope, T model, ExecutedResult result)
        {
            string cotrName = this.RouteData.Values["controller"].ToString();
            if (!FilterHelper.IsSysAdminAction(cotrName))
            {
                OperationLog.LogOperationData(new UserOperationLogModel
                {
                    CreateTime = DateTime.Now,
                    OperationTime = DateTime.Now,
                    OperationName = "添加",
                    ResourceName = cotrName,
                    UserName = scope.CurrentUserName,
                    UserRealName = scope.CurrentUserRealName,
                    ResultStatus = result.IsSucceed,
                    ErrorMsg = result.ErrorMsgTxt,
                    MainDataID = AlgCompare.GetPKID<ModelPKIDAttribute>(model)
                });
            }
        }

        public void LogUpdate(ScopeResult scope, T model, ExecutedResult result)
        {
            string cotrName = this.RouteData.Values["controller"].ToString();
            if (!FilterHelper.IsSysAdminAction(cotrName))
            {
                OperationLog.LogOperationData(new UserOperationLogModel
                {
                    CreateTime = DateTime.Now,
                    OperationTime = DateTime.Now,
                    OperationName = "修改",
                    ResourceName = cotrName,
                    UserName = scope.CurrentUserName,
                    UserRealName = scope.CurrentUserRealName,
                    ResultStatus = result.IsSucceed,
                    ErrorMsg = result.ErrorMsgTxt,
                    MainDataID = AlgCompare.GetPKID<ModelPKIDAttribute>(model)
                });
            }
        }

        public void LogDelete(Guid identity, ScopeResult scope, ExecutedResult result)
        {
            string cotrName = this.RouteData.Values["controller"].ToString();
            if (!FilterHelper.IsSysAdminAction(cotrName))
            {
                OperationLog.LogOperationData(new UserOperationLogModel
                {
                    CreateTime = DateTime.Now,
                    OperationTime = DateTime.Now,
                    OperationName = "删除",
                    ResourceName = cotrName,
                    UserName = scope.CurrentUserName,
                    UserRealName = scope.CurrentUserRealName,
                    ResultStatus = result.IsSucceed,
                    ErrorMsg = result.ErrorMsgTxt,
                    Data = identity.ToString()
                });
            }
        }

        public void LogBatchDelete(List<Guid> identities, ScopeResult scope, ExecutedResult result)
        {
            string cotrName = this.RouteData.Values["controller"].ToString();
            if (!FilterHelper.IsSysAdminAction(cotrName))
            {
                StringBuilder sb = new StringBuilder();
                identities.ForEach(i =>
                {
                    sb.Append(i);
                    sb.Append(",");
                });
                OperationLog.LogOperationData(new UserOperationLogModel
                {
                    CreateTime = DateTime.Now,
                    OperationTime = DateTime.Now,
                    OperationName = "删除",
                    ResourceName = cotrName,
                    UserName = scope.CurrentUserName,
                    UserRealName = scope.CurrentUserRealName,
                    ResultStatus = result.IsSucceed,
                    ErrorMsg = result.ErrorMsgTxt,
                    Data = sb.ToString()
                });
            }
        }
        #endregion

        #region IMicroHardControllerOperations<T> Members

        /// <summary>
        /// 列表页面
        /// </summary>
        /// <returns></returns>
        [MVCFilterAtrForLogon]//登录验证
        [MVCFilterAtrForResourcePermission]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult Index(ScopeResult scope)
        {
            int totalCount;
            List<T> rtn = null;
            GridModel gm = new GridModel();

            _repository.scope = scope;
            if (_isUsingPagingInIndex)
            {
                rtn = _repository.Query(new T(), 1, _pageSize, out totalCount);
                gm.Total = totalCount;
            }
            else
            {
                T model = new T();
                rtn = _repository.Query(model);
            }

            rtn.ForEach(i =>
            {
                //为字段中的字典显示字段赋值
                SetDictionaryFiledName.SetDicFiledTxtName<T>(ref i);
            });

            gm.Data = rtn;
            //记录操作
            this.LogIndex(scope);

            return View(gm);
        }

        /// <summary>
        /// 添加页面
        /// </summary>
        /// <returns></returns>
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult Create(Guid? newPKID, ScopeResult scope)
        {
            var model = new T();
            AlgCompare.SetPKIDPropertyValue<T>(ref model, newPKID);
            BasePermissionModel bpm = model as BasePermissionModel;
            if (bpm != null)
            {
                bpm.OperationStatus = OperationStatus.Add;
            }
            return View("Create", model);
        }

        /// <summary>
        /// 添加方法
        /// </summary>
        /// <param name="model"></param>
        /// <param name="continueEditing"></param>
        /// <returns></returns>
        [HttpPost]
        [ParameterBasedOnFormNameAttribute("save-continue", "continueEditing")]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Create")]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult SaveCreate([CustomizeValidator(RuleSet = "Insert")]T model, bool continueEditing, ScopeResult scope)
        {
            string newViewName = null;
            if (this.HttpContext.Items[SysConst.REDIRECTTONEWVIEW] != null)
            {
                newViewName = this.HttpContext.Items[SysConst.REDIRECTTONEWVIEW].ToString();
            }
            if (ModelState.IsValid)
            {
                _repository.scope = scope;
                var rtn = _repository.Add(model);
                rtn.ExecutedModel = model;
                this.HttpContext.Items["executedResult"] = rtn;

                //记录操作
                this.LogCreate(scope, model, rtn);

                if (!rtn.IsSucceed)
                {
                    StringBuilder errorMsg = new StringBuilder();
                    foreach (var err in rtn.ErrorMsg)
                    {
                        errorMsg.Append(err.Value);
                    }
                    TempData["executedResult"] = errorMsg.ToString();
                    return View((string.IsNullOrEmpty(newViewName) == false ? newViewName : "Create"), model);
                }
                else
                {

                    if (continueEditing)
                    {
                        var viewName = (string.IsNullOrEmpty(newViewName) == false ? newViewName : "Create");
                        return RedirectToAction(viewName);
                    }
                    else
                    {
                        var rm = scope.AfterActionExecuted;
                        if (rm != null)
                        {
                            BasePermissionModel bpm = model as BasePermissionModel;
                            //如果包含了跳转条件,则进行验证。
                            if (!string.IsNullOrEmpty(scope.AfterActionExecuted.Condition))
                            {
                                if (bpm.CurrentCondition != scope.AfterActionExecuted.Condition)
                                {
                                    return RedirectToAction("Index");
                                }
                            }
                            RouteValueDictionary queryString = new RouteValueDictionary { 
                       {"WeixinName",bpm.WeixinName},
                       {"WeixinToken",bpm.WeixinToken}};
                            if (!string.IsNullOrEmpty(rm.ResultModelExchangeParmsModelKeys))
                            {
                                var keys = Regex.Split(rm.ResultModelExchangeParmsModelKeys, ",");
                                foreach (var k in keys)
                                {
                                    string value = AlgCompare.GetValue(model, k);
                                    queryString.Add(k, value);
                                }
                            }
                            if (!string.IsNullOrEmpty(rm.RedirectAreaName))
                            {
                                queryString.Add("area", rm.RedirectAreaName);
                            }
                            return RedirectToAction(rm.RedirectActionName, rm.RedirectControllerName, queryString);
                        }
                        else
                        {
                            return RedirectToAction("Index");
                        }

                    }
                }
            }
            return View((string.IsNullOrEmpty(newViewName) ? "Create" : newViewName), model);
        }

        /// <summary>
        /// 暂存
        /// </summary>
        /// <param name="model"></param>
        /// <param name="continueEditing"></param>
        /// <returns></returns>
        [HttpPost]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Create")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "SaveCreate", OnExecutedFilterDataType = "SaveCreate")]//数据权限验证
        public virtual ActionResult TempSaveCreate([CustomizeValidator(RuleSet = "Insert")]T model, ScopeResult scope)
        {
            if (ModelState.IsValid)
            {
                _repository.scope = scope;
                var rtn = _repository.Add(model);
                rtn.ExecutedModel = model;
                this.HttpContext.Items["executedResult"] = rtn;

                //记录操作
                this.LogCreate(scope, model, rtn);

                if (!rtn.IsSucceed)
                {
                    StringBuilder errorMsg = new StringBuilder();
                    foreach (var err in rtn.ErrorMsg)
                    {
                        errorMsg.Append(err.Value);
                    }
                    TempData["executedResult"] = errorMsg.ToString();
                }
                else
                {
                    BasePermissionModel m = model as BasePermissionModel;
                    if (m != null)
                    {
                        m.OperationStatus = OperationStatus.TempSaveFinished;
                    }
                }
            }
            return View("Create", model);
        }

        /// <summary>
        /// 修改页面
        /// </summary>
        /// <param name="identity"></param>
        /// <returns></returns>
        [HttpPost]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult Update(Guid identity, ScopeResult scope)
        {
            _repository.scope = scope;
            var model = _repository.GetModelByID(identity);
            BasePermissionModel bpm = model as BasePermissionModel;
            if (bpm != null)
            {
                bpm.OperationStatus = OperationStatus.Update;
                //为字段中的字典显示字段赋值
                SetDictionaryFiledName.SetDicFiledTxtName<T>(ref model);
            }
            return View("Update", model);
        }


        [HttpPost]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Update")]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public ActionResult UpdateByModel(T model)
        {
            var updateModel = _repository.GetModelByModel(model);
            BasePermissionModel bpm = updateModel as BasePermissionModel;
            if (bpm != null)
            {
                bpm.OperationStatus = OperationStatus.Update;
                //为字段中的字典显示字段赋值
                SetDictionaryFiledName.SetDicFiledTxtName<T>(ref updateModel);
            }
            return View(updateModel);
        }

        /// <summary>
        /// 修改方法
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Update")]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult SaveUpdate([CustomizeValidator(RuleSet = "Update")]T model, ScopeResult scope)
        {
            if (ModelState.IsValid)
            {
                _repository.scope = scope;
                var rtn = _repository.Update(model);

                rtn.ExecutedModel = model;
                this.HttpContext.Items["executedResult"] = rtn;

                //记录操作
                this.LogUpdate(scope, model, rtn);

                if (rtn.IsSucceed)
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    StringBuilder errorMsg = new StringBuilder();
                    foreach (var err in rtn.ErrorMsg)
                    {
                        errorMsg.Append(err.Value);
                    }
                    TempData["executedResult"] = errorMsg.ToString();
                }
            }
            return View("Update", model);
        }

        /// <summary>
        /// 删除方法
        /// </summary>
        /// <param name="identities"></param>
        /// <returns></returns>
        [HttpPost]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult Delete(List<Guid> identities, ScopeResult scope)
        {
            _repository.scope = scope;
            var result = _repository.Delete(identities);

            //记录操作
            this.LogBatchDelete(identities, scope, result);

            if (result.IsSucceed)
            {
                this.HttpContext.Items["ToDeleteIds"] = identities;
                return new JsonResult { Data = "succeed" };
            }
            return new JsonResult { Data = result.ErrorMsgTxt };
        }

        [HttpPost]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Delete")]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult DeleteSingle(List<T> model, ScopeResult scope)
        {
            _repository.scope = scope;
            List<ExecutedResult> errors = new List<ExecutedResult>();
            List<Guid> forDelete = new List<Guid>();
            foreach (var m in model)
            {

                var result = _repository.Delete(m);
                if (!result.IsSucceed)
                {
                    errors.Add(result);
                }
                else
                {
                    forDelete.Add(result.Scope.PKID);
                }
                //记录操作
                this.LogDelete(result.Scope.PKID, scope, result);
            }
            bool isSucceed = false;
            StringBuilder errorMsg = new StringBuilder();
            if (errors.Count == 0)
            {
                this.HttpContext.Items["ToDeleteIds"] = forDelete;
                isSucceed = true;
            }
            else
            {
                foreach (var e in errors)
                {
                    errorMsg.AppendLine(e.ErrorMsg.First().Value);
                }
                isSucceed = false;
            }
            if (isSucceed)
            {
                return new JsonResult { Data = "succeed" };
            }
            return new JsonResult { Data = errorMsg.ToString() };
        }

        /// <summary>
        /// Grid分页调用
        /// </summary>
        /// <param name="command"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, GridAction(EnableCustomBinding = true)]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Index")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "index", OnExecutedFilterDataType = "index")]//数据权限验证
        public virtual ActionResult _List(GridCommand command, T model, ScopeResult scope)
        {
            _repository.scope = scope;
            int totalCount;
            var rtn = _repository.Query(model, command.Page, command.PageSize, out totalCount);

            rtn.ForEach(i =>
            {
                //为字段中的字典显示字段赋值
                SetDictionaryFiledName.SetDicFiledTxtName<T>(ref i);
            });

            var userModel = new GridModel()
            {
                Data = rtn,
                Total = totalCount
            };

            //记录操作
            this.LogIndex(scope);

            return new JsonResult
            {
                Data = userModel
            };
        }

        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Index")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "index", OnExecutedFilterDataType = "index")]//数据权限验证
        public virtual ActionResult _ListWithNoPaging(T model, ScopeResult scope)
        {
            _repository.scope = scope;
            var rtn = _repository.Query(model);

            rtn.ForEach(i =>
            {
                //为字段中的字典显示字段赋值
                SetDictionaryFiledName.SetDicFiledTxtName<T>(ref i);
            });

            var userModel = new GridModel()
            {
                Data = rtn
            };

            //记录操作
            this.LogIndex(scope);

            return new JsonResult
            {
                Data = userModel,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet

            };
        }

        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Create")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "Create", OnExecutedFilterDataType = "Create")]//数据权限验证
        public virtual ActionResult CreateWithParams(T model)
        {
            return View("Create", model);
        }

        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Index")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "index", OnExecutedFilterDataType = "index")]//数据权限验证
        public virtual ActionResult _GetSingleModel(Guid id)
        {
            var rtn = _repository.GetModelByID(id);

            //为字段中的字典显示字段赋值
            SetDictionaryFiledName.SetDicFiledTxtName<T>(ref rtn);

            return new JsonResult
            {
                Data = rtn,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        public virtual ActionResult _StartWorkFlow(List<Guid> approveWorkflowInstanceIds)
        {
            //List<ExecutedResult> errors = new List<ExecutedResult>();
            //IWorkflowApproveResult iwa = IoC.Resolve<IWorkflowApproveResult>();
            //foreach (var i in approveWorkflowInstanceIds)
            //{

            //    //流程审批，直接审批通过
            //    var rtn = iwa.Add(new ApproveWorkflow.Models.WorkflowApproveResultModel
            //    {
            //        DataID = i,
            //        TableName = this.Request.Url.ToString(),
            //        Status = (int)WorkflowResultStatus.Approve
            //    });

            //    if (!rtn.IsSucceed)
            //    {
            //        errors.Add(rtn);
            //    }
            //}
            //if (errors.Count == 0)
            //{
            //    return new JsonResult { Data = "succeed" };
            //}
            //else
            //{
            //    StringBuilder errorMsg = new StringBuilder();
            //    foreach (var e in errors)
            //    {
            //        errorMsg.AppendLine(e.ErrorMsg.First().Value);
            //    }
            //    return new JsonResult { Data = errorMsg.ToString() };
            //}
            return new JsonResult { Data = null };
        }

        [HttpPost]
        [ParameterBasedOnFormNameAttribute("save-continue", "continueEditing")]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Create")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "savecreate", OnExecutedFilterDataType = "savecreate")]//数据权限验证
        public virtual ActionResult _AjaxSaveCreate([CustomizeValidator(RuleSet = "Insert")]T model, ScopeResult scope)
        {
            List<T> result = new List<T>();
            int totalCount = 0;
            _repository.scope = scope;

            if (ModelState.IsValid)
            {
                var rtn = _repository.Add(model);
                rtn.ExecutedModel = model;
                this.HttpContext.Items["executedResult"] = rtn;

                //记录操作
                this.LogCreate(scope, model, rtn);

                if (!rtn.IsSucceed)
                {
                    StringBuilder errorMsg = new StringBuilder();
                    foreach (var err in rtn.ErrorMsg)
                    {
                        errorMsg.Append(err.Value);
                    }
                }
            }
            if (this._isUsingPagingInIndex)
            {
                int pageSize = int.Parse(ConfigurationManager.AppSettings["GridPageSize"]);
                result = _repository.Query(model, 1, pageSize, out totalCount);
            }
            else
            {
                result = _repository.Query(model);
            }
            result.ForEach(i =>
            {
                //为字段中的字典显示字段赋值
                SetDictionaryFiledName.SetDicFiledTxtName<T>(ref i);
            });
            var userModel = new GridModel()
            {
                Data = result,
                Total = totalCount
            };
            return new JsonResult
            {
                Data = userModel
            };
        }

        [HttpPost]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Update")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "saveupdate", OnExecutedFilterDataType = "saveupdate")]//数据权限验证
        public virtual ActionResult _AjaxSaveUpdate([CustomizeValidator(RuleSet = "Update")]T model, ScopeResult scope)
        {
            List<T> result = new List<T>();
            int totalCount = 0;

            if (ModelState.IsValid)
            {
                _repository.scope = scope;
                var rtn = _repository.Update(model);

                rtn.ExecutedModel = model;
                this.HttpContext.Items["executedResult"] = rtn;

                //记录操作
                this.LogUpdate(scope, model, rtn);

                if (!rtn.IsSucceed)
                {
                    StringBuilder errorMsg = new StringBuilder();
                    foreach (var err in rtn.ErrorMsg)
                    {
                        errorMsg.Append(err.Value);
                    }
                    TempData["executedResult"] = errorMsg.ToString();
                }
            }
            if (this._isUsingPagingInIndex)
            {
                int pageSize = int.Parse(ConfigurationManager.AppSettings["GridPageSize"]);
                result = _repository.Query(model, 1, pageSize, out totalCount);
            }
            else
            {
                result = _repository.Query(model);
            }
            result.ForEach(i =>
            {
                //为字段中的字典显示字段赋值
                SetDictionaryFiledName.SetDicFiledTxtName<T>(ref i);
            });
            var userModel = new GridModel()
            {
                Data = result,
                Total = totalCount
            };
            return new JsonResult
            {
                Data = userModel
            };
        }


        [HttpPost]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Delete")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "deletesingle", OnExecutedFilterDataType = "deletesingle")]//数据权限验证
        public virtual ActionResult _AjaxDelete(T model, ScopeResult scope)
        {
            List<T> result = new List<T>();
            int totalCount = 0;

            _repository.scope = scope;
            //获得主键
            var pkid = AlgCompare.GetPKID<ModelPKIDAttribute>(model);
            var ids = new List<Guid>();
            ids.Add(pkid);
            var rtn = _repository.Delete(ids);
            //记录操作
            this.LogDelete(pkid, scope, rtn);

            if (this._isUsingPagingInIndex)
            {
                int pageSize = int.Parse(ConfigurationManager.AppSettings["GridPageSize"]);
                result = _repository.Query(model, 1, pageSize, out totalCount);
            }
            else
            {
                result = _repository.Query(model);
            }
            result.ForEach(i =>
            {
                //为字段中的字典显示字段赋值
                SetDictionaryFiledName.SetDicFiledTxtName<T>(ref i);
            });
            var userModel = new GridModel()
            {
                Data = result,
                Total = totalCount
            };
            return new JsonResult
            {
                Data = userModel
            };
        }

        [MVCFilterAtrForLogon(Order = 1)]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Update", Order = 2)]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "update", OnExecutedFilterDataType = "update", Order = 3)]//数据权限验证
        public virtual ActionResult StartWorkflow(Guid identity, string approvers, ScopeResult scope, bool isWorkflowStarted)
        {
            if (isWorkflowStarted)
            {
                _repository.scope = scope;
                IWorkflow wf = _repository as IWorkflow;
                if (wf != null)
                {
                    var obj = wf.Start(identity, Guid.Empty, approvers);
                    if (obj != null)
                    {
                        this.HttpContext.Items["executedResult"] = obj;

                        //记录操作
                        OperationLog.LogOperationData(new UserOperationLogModel
                        {
                            CreateTime = DateTime.Now,
                            OperationTime = DateTime.Now,
                            OperationName = "发起流程",
                            ResourceName = this.RouteData.Values["controller"].ToString(),
                            ResultStatus = true,
                            UserName = scope.CurrentUserName,
                            UserRealName = scope.CurrentUserRealName,
                            MainDataID = identity
                        });
                    }
                }
            }
            return RedirectToAction("Index");
        }

        /// <summary>
        /// 查看页面
        /// </summary>
        /// <param name="identity"></param>
        /// <returns></returns>
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "View")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "update", OnExecutedFilterDataType = "update")]//数据权限验证
        public virtual ActionResult _AjaxViewDetail(Guid identity, ScopeResult scope)
        {
            _repository.scope = scope;
            var model = _repository.GetModelByID(identity);
            BasePermissionModel bpm = model as BasePermissionModel;
            if (bpm != null)
            {
                bpm.OperationStatus = OperationStatus.Update;
                //为字段中的字典显示字段赋值
                SetDictionaryFiledName.SetDicFiledTxtName<T>(ref model);
            }
            return View("ViewDetail", model);
        }

        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="identity"></param>
        /// <param name="scope"></param>
        /// <returns></returns>
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Update")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "update", OnExecutedFilterDataType = "update")]//数据权限验证
        public virtual ActionResult _POSPrint(Guid identity, ScopeResult scope)
        {
            _repository.scope = scope;
            var model = _repository.GetModelByID(identity);
            string printContent = model.CreateContent();
            POSPrinterTool pst = new POSPrinterTool();
            string ip = System.Configuration.ConfigurationManager.AppSettings["POSIP"];
            int port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["POSPort"]);
            var rtn = pst.SendToPrint(ip, port, printContent);
            if (rtn.IsSucceed)
            {
                return Json("true", JsonRequestBehavior.AllowGet);
            }
            return Json("false", JsonRequestBehavior.AllowGet);
        }
        #endregion

    }
}
